#!/usr/bin/python
#-*- coding: utf-8 -*-

import sys
reload(sys)
sys.setdefaultencoding('utf8')

from  salt_api import SaltAPI

import threading
import ConfigParser
import  db, conf
import MySQLdb

conn, cur = db.db_object()

asset_info = []

class Cmdb(object):
    """docstring for Cmdb"""

    def __init__(self):
        self.conn, self.cur = db.db_object()

    # 机房方法
    # 添加机房
    def add_room(self, info):
        query = 'INSERT INTO room(info) VALUES("{info}")'.format(info=info)
        try:
            self.cur.execute(query)
            self.conn.commit()
            return {'code': 0, 'message': '添加机房  {0}  成功'.format(info)}
        except Exception, e:
            return {'code': 202, 'message': '数据库执行失败' + str(e)}

    # 修改机房
    def edit_room(self, id, info):
        query = 'UPDATE room set info="{info}" WHERE id="{id}"'.format(id=id,
                                                                       info=info)
        try:
            self.cur.execute(query)
            self.conn.commit()
            return {'code': 0, 'message': '修改机房  {0}  成功'.format(info)}
        except Exception, e:
            return {'code': 202, 'message': '数据库执行失败' + str(e)}

    # 删除机房
    def del_room(self, id):
        query = 'DELETE fROM room WHERE id="{id}"'.format(id=id)
        try:
            self.cur.execute(query)
            self.conn.commit()
            return {'code': 0, 'message': '删除机房成功'}
        except Exception, e:
            return {'code': 202, 'message': '数据库执行失败' + str(e)}

    # 机房列表
    def list_room(self):
        query = 'SELECT id,info FROM room'
        try:
            self.cur.execute(query)
            data = self.cur.fetchall()
            return {'code': 0, 'message': '获取机房列表成功', 'data': data}
        except Exception, e:
            return {'code': 202, 'message': '数据库执行失败' + str(e)}

    # 机柜方法
    # 添加机柜
    def add_cabinet(self, info):
        query = 'INSERT INTO cabinet(info) VALUES("{info}")'.format(info=info)
        self.cur.execute(query)
        self.conn.commit()
        return {'code': 0, 'message': '添加机柜  {0}  成功'.format(info)}

    # 删除机柜
    def del_cabinet(self, id):
        query = 'DELETE fROM cabinet WHERE id="{id}"'.format(id=id)
        self.cur.execute(query)
        self.conn.commit()
        return {'code': 0, 'message': '删除机柜成功'}

    # 机柜列表
    def list_cabinet(self):
        query = 'SELECT id,info FROM cabinet'
        self.cur.execute(query)
        data = self.cur.fetchall()
        return {'code': 0, 'message': '获取机柜列表成功', 'data': data}

    # 修改机柜
    def edit_cabinet(self, id, info):
        query = 'UPDATE cabinet set info="{info}" WHERE id="{id}"'.format(id=id,
                                                                          info=info)
        self.cur.execute(query)
        self.conn.commit()
        return {'code': 0, 'message': '修改机柜成功'}

    ## 主机方法
    ## 自动采集主机信息
    def get_server_asset_info(self, tgt, url, user, passwd, device):
        '''
        Salt API得到资产信息，进行格式化输出
        '''

        cf = ConfigParser.ConfigParser()
        cf.read('config.ini')

        global asset_info
        info = []
        sapi = SaltAPI(url=url, username=user, password=passwd)
        ret = sapi.remote_noarg_execution(tgt, 'discovery.Discovery')
        host_id = ret['id']
        info.append(host_id)
        host_ip = ret['ip4_interfaces'][device][0]
        info.append(host_ip)
        ret["hwaddr_interfaces"].pop("lo")
        hwaddr_interfaces = ret["hwaddr_interfaces"]['eth0']
        info.append(hwaddr_interfaces)
        cpu_model = ret['cpu_model']
        info.append(cpu_model)
        num_cpus = int(ret['num_cpus'])
        info.append(num_cpus)
        mem_total = ret['mem_total']
        info.append(mem_total)
        disk_size = ret['disk_size']
        info.append(disk_size)
        kernelrelease = ret['kernelrelease']
        info.append(kernelrelease)
        sys_ver = ret['osfullname'] + ret['osrelease'] + '-' + ret['osarch']
        info.append(sys_ver)
        vt = ret['virtual']
        info.append(vt)
        asset_info.append(info)
        #return asset_info


    ##自动采集主机入库

        cur.execute('select host_id from salt_stack')  ###获取资产列表中的主机名
        result = cur.fetchone()
        if result:
            hostname = result[0]
        else:
            hostname = None

        print host_id , hostname

        if host_id != hostname:  ##判断主机是否已经入库，如果存在输出提示，不存在则入库
            T = [host_id,host_ip, cpu_model, num_cpus, hwaddr_interfaces, mem_total,
                  disk_size, sys_ver, kernelrelease]
            for x in T:
                print type(x),x


            sql = '''
                    INSERT INTO
                    salt_stack(host_id,host_ip,cpu_model,num_cpus,hwaddr_interfaces,mem_total,disk_size,sys_ver,kernelrelease)
                    VALUES('{host_id}',
                    '{host_ip}',
                    '{cpu_model}',
                    '{num_cpus}',
                    '{hwaddr_interfaces}',
                    '{mem_total}',
                    '{disk_size}',
                    '{sys_ver}',
                    '{kernelrelease}')
            '''.format(host_id=host_id,
                       host_ip=host_ip,
                       cpu_model=cpu_model,
                       num_cpus=num_cpus,
                       hwaddr_interfaces=hwaddr_interfaces,
                       mem_total=mem_total,
                       disk_size=disk_size,
                       sys_ver=sys_ver,
                       kernelrelease=kernelrelease)
            self.cur.execute(sql)
            self.conn.commit()
            self.conn.close()

        elif host_id in hostname:  ## 判断机器是否在列表，在则提示，不在则添加
            print 'The machine you added already exists'
        else:
            return {'code': 0, 'message': '添加机器成功'}






    ## 修改主机信息
    def edit_host(self,id,host_ip,cpu_model,num_cpus,hwaddr_interfaces,mem_total,disk_size,sys_ver,kernelrelease,
                  appliction,room_id,cabinet_id,location):
        query = '''
            UPDATE
                salt_stack
            SET
                host_ip='{host_ip}'
                cpu_model='{cpu_model}'
                num_cpus='{num_cpus}'
                hwaddr_interfaces='{hwaddr_interfaces}'
                mem_total='{mem_total}'
                disk_size='{disk_size}'
                sys_ver='{sys_ver}'
                kernelrelease='{kernelrelease}'
                appliction='{appliction}'
                room_id='{room_id}'
                cabinet_id='{cabinet_id}'
                location='{location}'
            WHERE
                id='{id}'

        '''.format(
            id=id,
            host_ip=host_ip,
            cpu_model=cpu_model,
            num_cpus=num_cpus,
            hwaddr_interfaces=hwaddr_interfaces,
            mem_total=mem_total,
            disk_size=disk_size,
            sys_ver=sys_ver,
            kernelrelease=kernelrelease,
            appliction=appliction,
            room_id=room_id,
            cabinet_id=cabinet_id,
            location=location
        )

        self.cur.execute(query)
        self.conn.commit()
        self.conn.close()
        return {'code': 0, 'message': '修改机器成功'}


    ## 删除主机信息
    def del_host(self,id):
        query = 'DELETE FROM salt_stack WHERE id="{id}"'.format(id=id)
        self.cur.execute(query)
        self.conn.commit()
        self.conn.close()
        return {'code': 0, 'message': '删除机器成功'}

    ## 修改主机
    def list_host(self):
        query = '''
            SELECT
                    salt_stack.id,
                    appliction,
                    host_id,
                    host_ip,
                    cpu_model,
                    num_cpus,
                    mem_total,
                    disk_size,
                    room.info AS room_info,
                    cabinet.info AS cabinet_info,
                    location
            FROM
                    salt_stack,
                    room,
                    cabinet
            WHERE
                    salt_stack.room_id = room.id AND
                    salt_stack.cabinet_id = cabinet.id
                '''
        self.cur.execute(query)
        self.conn.commit()
        data = self.cur.fetchall()
        return {'code': 0, 'message': '获取机器列表成功', 'data': data}

if __name__ == '__main__':
    c =Cmdb()
    print c.get_server_asset_info('Home-Flask-kk','https://192.168.0.12:8000','saltapi','saltapi','eth0')
    #print c.del_host(27)
    ##print del_host(25)












